import { useMemo } from 'react';
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer, 
  PieChart, 
  Pie, 
  Cell 
} from 'recharts';
import { useStore, Plan, CheckIn } from '@/lib/hooks/useStore';
import { format, startOfWeek, addDays, parseISO, differenceInDays } from 'date-fns';
import { zhCN } from 'date-fns/locale';

export function PlanStats() {
  const { plans, checkIns } = useStore();
  
  // 每周打卡统计数据
  const weeklyCheckInData = useMemo(() => {
    const today = new Date();
    const startOfWeekDate = startOfWeek(today, { weekStartsOn: 1 }); // 从周一开始
    
    const days = [];
    for (let i = 0; i < 7; i++) {
      const day = addDays(startOfWeekDate, i);
      const dayString = format(day, 'EEE', { locale: zhCN });
      const dayDate = format(day, 'yyyy-MM-dd');
      
      const checkInsCount = checkIns.filter(checkIn => 
        format(new Date(checkIn.date), 'yyyy-MM-dd') === dayDate
      ).length;
      
      days.push({
        name: dayString,
        打卡数: checkInsCount,
      });
    }
    
    return days;
  }, [checkIns]);
  
  // 计划完成情况统计
  const planCompletionData = useMemo(() => {
    const completed = plans.filter(plan => plan.isCompleted).length;
    const inProgress = plans.length - completed;
    
    return [
      { name: '已完成', value: completed },
      { name: '进行中', value: inProgress },
    ];
  }, [plans]);
  
  // 计算进度比例
  const calculateProgress = (plan: Plan, planCheckIns: CheckIn[]) => {
    if (!plan.endDate) return 0;
    
    const totalDays = differenceInDays(new Date(plan.endDate), new Date(plan.startDate)) + 1;
    if (totalDays <= 0) return 0;
    
    const uniqueDates = new Set(
      planCheckIns.map(checkIn => format(new Date(checkIn.date), 'yyyy-MM-dd'))
    );
    
    return (uniqueDates.size / totalDays) * 100;
  };
  
  // 计划进度数据
  const planProgressData = useMemo(() => {
    return plans.map(plan => {
      const planCheckIns = checkIns.filter(checkIn => checkIn.planId === plan.id);
      const progress = calculateProgress(plan, planCheckIns);
      
      return {
        name: plan.title.length > 10 ? plan.title.substring(0, 10) + '...' : plan.title,
        进度: Math.min(Math.round(progress), 100),
      };
    });
  }, [plans, checkIns]);
  
  const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8'];
  
  if (plans.length === 0) {
    return (
      <div className="bg-white rounded-lg shadow-md p-6 text-center">
        <p className="text-gray-500">还没有计划数据，请先添加计划</p>
      </div>
    );
  }
  
  return (
    <div className="bg-white rounded-lg shadow-md p-6 space-y-8">
      <div>
        <h3 className="text-lg font-semibold mb-4">每周打卡情况</h3>
        <div className="h-64">
          <ResponsiveContainer width="100%" height="100%">
            <BarChart
              data={weeklyCheckInData}
              margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
            >
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" />
              <YAxis allowDecimals={false} />
              <Tooltip />
              <Bar dataKey="打卡数" fill="#8884d8" barSize={30} />
            </BarChart>
          </ResponsiveContainer>
        </div>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <h3 className="text-lg font-semibold mb-4">计划完成情况</h3>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={planCompletionData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  fill="#8884d8"
                  paddingAngle={5}
                  dataKey="value"
                  label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`}
                >
                  {planCompletionData.map((_, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </div>
        
        <div>
          <h3 className="text-lg font-semibold mb-4">计划进度</h3>
          <div className="h-64">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart
                layout="vertical"
                data={planProgressData}
                margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis type="number" domain={[0, 100]} />
                <YAxis type="category" dataKey="name" />
                <Tooltip />
                <Bar dataKey="进度" fill="#82ca9d" barSize={20} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </div>
      </div>
    </div>
  );
} 